import { mapMutations } from 'vuex'
import { post } from '@/servers/http'

const ruleMix={
  methods: {
    ...mapMutations('main', [
      'editComponent',
      'addComponentListItem',
      'removeComponentListField',
      'editComponentListItem',
      'updateChildListModelField'
    ]),
    ...mapMutations('step', ['stepsAdd1', 'stepLock']),
    prefixConditionValueChange (row) {
      row.suffixConditionValue = ''
    },
    prefixConditionChange (row) {
      row.prefixConditionValue = ''
      row.operation = ''
      row.suffixCondition = ''
      row.suffixConditionValue = ''
    },
    inputChange (row) {
      if (row.prefixCondition === 'userSegmentRule' && row.prefixConditionValue === 'userSegment') {
        if (row.suffixConditionValue) {
          // 验证输入的人群包编号是否有效
          post('/rule/querySegmentBatch', { segmentCode: row.suffixConditionValue }).then(res => {
            if (res.flag === 'S') {
              if (!res.data.flag) {
                // this.$message.info(res.data);
                let error = []
                if (res.data.notExistList && res.data.notExistList.length > 0) {
                  error.push(`不存在的编号：${res.data.notExistList.join('，')}`)
                }
                if (res.data.expireList && res.data.expireList.length > 0) {
                  error.push(`过期的编号：${res.data.expireList.join('，')}`)
                }
                if (res.data.unUseList && res.data.unUseList.length > 0) {
                  error.push(`不可用的编号：${res.data.unUseList.join('，')}`)
                }
                this.$alert(error.join('</br>'), '人群包编号异常', {
                  dangerouslyUseHTMLString: true,
                  confirmButtonText: '确定',
                  callback: () => {
                  }
                })
              }
            } else {
              this.$message.error(res.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
        }
      }
    },
    checkCode (row) {
      if (row.suffixConditionValue) {
        // 验证输入的人群包编号是否有效
        post('/rule/querySegmentBatch', { segmentCode: row.suffixConditionValue }).then(res => {
          if (res.flag === 'S') {
            if (!res.data.flag) {
              // this.$message.info(res.data);
              let error = []
              if (res.data.notExistList && res.data.notExistList.length > 0) {
                error.push(`不存在的编号：${res.data.notExistList.join('，')}`)
              }
              if (res.data.expireList && res.data.expireList.length > 0) {
                error.push(`过期的编号：${res.data.expireList.join('，')}`)
              }
              if (res.data.unUseList && res.data.unUseList.length > 0) {
                error.push(`不可用的编号：${res.data.unUseList.join('，')}`)
              }
              this.$alert(error.join('</br>'), '人群包编号异常', {
                dangerouslyUseHTMLString: true,
                confirmButtonText: '确定',
                callback: () => {
                }
              })
            }
          } else {
            this.$message.error(res.msg)
          }
        }).catch(err => {
          this.$message.error(err)
        })
      } else {
        this.$message.error('请输入人群包规则编号！')
      }
    },
    prefixConditionOptions (row) {
      if (row) {
        let node = this.configData.condition.find(
          a => a.preType === row.prefixCondition
        )
        return node ? node.rules : []
      } else {
        return []
      }
    },
    rightCondition (row) {
      let rules = this.prefixConditionOptions(row)
      let ruleNode = rules.find(a => a.ruleType === row.prefixConditionValue)
      if (ruleNode) {
        let sufType = ruleNode.sufType
        let list = this.configData.conditionType.filter(
          a => a.value === sufType
        )
        if (list) {
          row.suffixCondition = list[0].value
          return list
        } else {
          return []
        }
      } else {
        return []
      }
    },
    rightValue (row) {
      let rules = this.prefixConditionOptions(row)
      let ruleNode = rules.find(a => a.ruleType === row.prefixConditionValue)
      if (ruleNode) {
        let result = ruleNode.result
        let node = this.configData.resultType.find(
          a => a.code.toString() === result
        )
        if (node) {
          return node
        } else {
          return {}
        }
      } else {
        return {}
      }
    },
    rightValueOptions (row) {
      let node = this.rightValue(row)
      if (Number(node.type) === 1 || Number(node.type) === 2 || Number(node.type) ===6) {
        let arrName = new Array()
        let arrValue = new Array()
        arrName = node.name.split(',')
        arrValue = node.value.split(',')
        let result = new Array()
        for (let k = 0; k < arrName.length; k++) {
          result.push({ name: arrName[k], value: arrValue[k] })
        }
        return result
      } else {
        return []
      }
    },
    rightSelectShow (row) {
      let code = this.rightValue(row).type
      // 单选
      if (Number(code) === 2) {
        return true
      } else {
        return false
      }
    },
    rightSelectShowMultiple (row) {
      let code = this.rightValue(row).type
      // 多选
      if (Number(code) === 1 || Number(code) === 6) {
        return true
      } else {
        return false
      }
    },
    rightInputShow (row) {
      let code = this.rightValue(row).type
      // 输入项
      if (Number(code) === 3 || Number(code) === 4) {
        return true
      } else {
        return false
      }
    },
    rightRangeShow (row) {
      let code = this.rightValue(row).type
      // 区间
      if (Number(code) === 5 || Number(code) === 6) {
        return true
      } else {
        return false
      }
    },
    rightProductRangeShow (row) {
      let code = this.rightValue(row).type
      // 区间
      if (Number(code) === 6) {
        return true
      } else {
        return false
      }
    },
    rightCheckIconShow (row) {
      let code = this.rightValue(row).type
      // 右侧输入刷新按钮
      if (Number(code) === 3) {
        return true
      } else {
        return false
      }
    },
    operationOptions (row) {
      let rules = this.prefixConditionOptions(row)
      if (rules && rules.length > 0) {
        let xnode = rules.find(a => a.ruleType === row.prefixConditionValue)
        if (xnode) {
          let ops = new Array()
          ops = xnode.operator.split(',')
          let opList = this.configData.operators.filter(a =>
            ops.includes(a.value)
          )
          return opList
        } else {
          return []
        }
      } else {
        return []
      }
    },
    ok () {
      let _this = this
      let data = {
        activityCode: _this.activityCode,
        moduleCode: _this.comModuleCode,
        groupCode: '',
        ruleRelation: '',
        onlineTime: null,
        offlineTime: null,
        ruleDescription: '',
        ruleList: [],
        userNo: ''
      }
      const checkList = ['CouponModule', 'CouponPackageModule']
      if (checkList.includes(this.componentModel.code) && this.ruleList.length > 0 && (!this.startEnd || this.startEnd.length === 0)) {
        this.$message.error('该组件的人群规则，必须设置【组件上架时间】')
        return
      }
      for (let i = 0; i < this.ruleList.length; i++) {
        if (this.ruleList[i].ruleDetailList.length === 0) {
          this.$message.error('第' + (i + 1) + '组至少添加一条规则')
          return
        }
        let details = this.ruleList[i].ruleDetailList
        for (let k = 0; k < details.length; k++) {

          if (details[k].prefixConditionValue==='JtCreditDayRuleProcessor'){
            // 首次授信天数
            if (!details[k].operation){
              this.$message.error(
                '第' + (i + 1) + '组，第' + (k + 1) + '条规则：信息填写不完整！'
              )
              return
            }
            if (isNaN(details[k].startValue) || isNaN(details[k].endValue)){
              this.$message.error(
                '第' + (i + 1) + '组，第' + (k + 1) + '条规则：授信天数填写不正确，只能为数字！'
              )
              return
            } 
            if (Number(details[k].startValue)>Number(details[k].endValue)){
              this.$message.error(
                '第' + (i + 1) + '组，第' + (k + 1) + '条规则：授信天数，结束值不能小于开始值！'
              )
              return
            }   
          } else if (details[k].prefixConditionValue==='userProductMaxRemainAmountRuleV2Processor'){
            // 剩余可用额度
            if (!details[k].operation){
              this.$message.error(
                '第' + (i + 1) + '组，第' + (k + 1) + '条规则：信息填写不完整！'
              )
              return
            }
            if (!details[k].suffixConditionValue || details[k].suffixConditionValue.length===0 || isNaN(details[k].startValue) || isNaN(details[k].endValue)){
              this.$message.error(
                '第' + (i + 1) + '组，第' + (k + 1) + '条规则：产品或额度填写不正确！'
              )
              return
            }
            if (Number(details[k].startValue)>Number(details[k].endValue)){
              this.$message.error(
                '第' + (i + 1) + '组，第' + (k + 1) + '条规则：可用额度，结束值不能小于开始值！'
              )
              return
            }      
               
          } else {
            // 其他
            if (
              !details[k].prefixCondition ||
            !details[k].prefixConditionValue ||
            !details[k].operation ||
            !details[k].suffixConditionValue
            ) {
              this.$message.error(
                '第' + (i + 1) + '组，第' + (k + 1) + '条规则：信息填写不完整！'
              )
              return
            }
          }

          
        }
      }

      if (this.startEnd && this.startEnd.length > 0) {
        data.onlineTime = this.startEnd[0]
        data.offlineTime = this.startEnd[1]
      }
      data.ruleRelation = this.relation ? 'and' : 'or'
      data.ruleDescription = this.ruleDescription
      let list = JSON.parse(JSON.stringify(this.ruleList))
      for (let m = 0; m < list.length; m++) {
        list[m].ruleRelation = list[m].ruleRelation ? 'and' : 'or'
        list[m].sortNum = m
        let detailList = list[m].ruleDetailList
        for (let n = 0; n < detailList.length; n++) {
          // alert(JSON.stringify(detailList[n]))
          // return

          if (detailList[n].prefixConditionValue==='JtCreditDayRuleProcessor'){
            // 首次授信天数
            detailList[n].suffixConditionValue =JSON.stringify({
              'minCreditDays':detailList[n].startValue,
              'maxCreditDays':detailList[n].endValue
            })
               
          } else if (detailList[n].prefixConditionValue==='userProductMaxRemainAmountRuleV2Processor'){
            // 剩余可用额度
            detailList[n].suffixConditionValue =JSON.stringify({
              'productCodeList':detailList[n].suffixConditionValue,
              'minRemainAmount':detailList[n].startValue,
              'maxRemainAmount':detailList[n].endValue
            })
               
          } else {
            // 其他常规多选
            if (detailList[n].suffixConditionValue instanceof Array) {
              detailList[n].suffixConditionValue = detailList[
                n
              ].suffixConditionValue.join(',')
            }
          }
          
          detailList[n].sortNum = n
        }
      }
      data.ruleList = list
      if (this.searchResult && this.searchResult.groupCode) {
        data.groupCode = this.searchResult.groupCode
      }

      let requestUrl = (this.ruleType === 'content' || this.ruleType === 'quota') ? '/rule/saveElementRuleResult' : '/rule/saveRuleResult'
      if (this.ruleType === 'content' || this.ruleType === 'quota') {
        data.elementCode = this.elementCode
      }
      post(requestUrl, data)
        .then(res => {
          if (res.flag === 'S') {
            _this.$emit('callback', data)
            _this.dialogVisible = false
          } else {
            _this.$message.error(res.msg)
          }
        })
        .catch(err => {
          _this.$message.error('保存失败：' + JSON.stringify(err))
        })
    },
    openDialog () {
      let _this = this
      this.clearDialog()
      this.dialogVisible = true
      setTimeout(function () {
        _this.queryRule()
      }, 200)
    },
    clearDialog () {
      this.startEnd = []
      this.ruleDescription = ''
      this.relation = true
      this.ruleList = []
    },
    queryRule () {
      let _this = this
      this.searchResult = {}
      let requestUrl = (this.ruleType === 'content' || this.ruleType === 'quota') ? '/rule/queryElementRuleResult' : '/rule/queryRuleResult'
      post(requestUrl,
        { elementCode: this.elementCode, activityCode: this.activityCode, moduleCode: this.comModuleCode }
      ).then(res => {
        if (res.flag === 'S') {
          if (!res.data || !res.data.ruleRelation) {
            return
          }
          this.searchResult = res.data
          if (res.data.onlineTime && res.data.onlineTime) {
            _this.startEnd = [new Date(_this.formatDate(Number(res.data.onlineTime))), new Date(_this.formatDate(Number(res.data.offlineTime)))]
          }
          this.ruleDescription = res.data.ruleDescription
          this.relation = res.data.ruleRelation === 'or' ? false : true

          let list = JSON.parse(JSON.stringify(res.data.ruleList))
          for (let m = 0; m < list.length; m++) {
            list[m].ruleRelation =
              list[m].ruleRelation === 'and' ? true : false
            let detailList = list[m].ruleDetailList
            for (let n = 0; n < detailList.length; n++) {

              if (detailList[n].prefixConditionValue==='JtCreditDayRuleProcessor'){
                // 首次授信天数
                const range = JSON.parse(detailList[n].suffixConditionValue) 
                detailList[n].startValue =range.minCreditDays
                detailList[n].endValue =range.maxCreditDays
              } else if (detailList[n].prefixConditionValue==='userProductMaxRemainAmountRuleV2Processor'){
                // 剩余可用额度
                const range = JSON.parse(detailList[n].suffixConditionValue) 
                detailList[n].startValue =range.minRemainAmount
                detailList[n].endValue =range.maxRemainAmount
                detailList[n].suffixConditionValue=range.productCodeList
              } else {
                if (_this.rightSelectShowMultiple(detailList[n])) {
                // 非 input ,即 数组
                  detailList[n].suffixConditionValue = detailList[
                    n
                  ].suffixConditionValue.split(',')
                }
              } 
            }
          }
          this.ruleList = list
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    addGroup () {
      this.ruleList.push({
        groupCode: '',
        ruleCode: '',
        ruleRelation: true,
        sortNum: 0,
        ruleDetailList: [
          {
            id: '',
            ruleCode: '',
            prefixCondition: '',
            prefixConditionValue: '',
            operation: '',
            suffixCondition: '',
            suffixConditionValue: '',
            sortNum: 0
          }
        ]
      })
    },
    addItem (group) {
      let item = {
        id: '',
        ruleCode: '',
        prefixCondition: '',
        prefixConditionValue: '',
        operation: '',
        suffixCondition: '',
        suffixConditionValue: '',
        sortNum: 0
      }
      group.ruleDetailList.push(item)
    },
    deleteGroup (index, item) {
      let _this = this
      if (item.groupCode) {
        this.$confirm('此操作将删除该规则组（立即生效）, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let requestUrl = (this.ruleType === 'content' || this.ruleType === 'quota') ? '/rule/removeElementRule' : '/rule/removeRule'
          post(requestUrl, {
            elementCode: _this.elementCode,
            groupCode: item.groupCode,
            ruleCode: item.ruleCode,
            activityCode: _this.activityCode,
            moduleCode: _this.comModuleCode
          }).then(res => {
            if (res.flag === 'S') {
              _this.ruleList.splice(index, 1)
            } else {
              this.$message.error(res.msg)
            }
          })
        })
      } else {
        _this.ruleList.splice(index, 1)
      }
    },
    removeItem (parentIndex, index, item) {
      let _this = this
      if (item.id) {
        this.$confirm('此操作将删除该规则（立即生效）, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let requestUrl = (this.ruleType === 'content' || this.ruleType === 'quota') ? '/rule/removeElementRule' : '/rule/removeRule'
          post(requestUrl, {
            id: item.id,
            elementCode: _this.elementCode,
            activityCode: _this.activityCode,
            moduleCode: _this.comModuleCode
          }).then(res => {
            if (res.flag === 'S') {
              _this.ruleList[parentIndex].ruleDetailList.splice(index, 1)
            } else {
              this.$message.error(res.msg)
            }
          })
        })
      } else {
        _this.ruleList[parentIndex].ruleDetailList.splice(index, 1)
      }

    },
    formatDate (value) {
      if (!value || value === '') {
        return ''
      }
      let date = new Date(value)
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        S: date.getMilliseconds()
      }
      let fmt = 'yyyy-MM-dd hh:mm:ss'
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
      for (let k in o)
        if (new RegExp('(' + k + ')').test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? o[k]
              : ('00' + o[k]).substr(('' + o[k]).length)
          )
      return fmt
    }
  }
}

export default ruleMix